using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using Rensselaer_Event_Finder.Hibernate.DAO;

namespace Rensselaer_Event_Finder.Hibernate
{
    /**
     * Class to configure NHibernate.
     * Itloads the hibernate mappings and the app.config file 
     * which stores information on how to connect to the database.
     * Handles the opening of new sessions.
     **/
    public class NHibernateHelper 
    {
        public static readonly ISessionFactory sessionFactory;
        public static ISession session;

        /* Configuration */
        static NHibernateHelper()
        {
            try
            {
                Configuration cfg = new Configuration();
                cfg.Configure().AddXmlFile("Hibernate/Mappings/Category.hbm.xml")
                               .AddXmlFile("Hibernate/Mappings/Event.hbm.xml")
                                .AddXmlFile("Hibernate/Mappings/Location.hbm.xml")
                                .AddXmlFile("Hibernate/Mappings/EventComment.hbm.xml")
                                .AddXmlFile("Hibernate/Mappings/LocationComment.hbm.xml")
                                .AddXmlFile("Hibernate/Mappings/LocationRating.hbm.xml")
                                .AddXmlFile("Hibernate/Mappings/User.hbm.xml")
                                .AddXmlFile("Hibernate/Mappings/Sync.hbm.xml");
                sessionFactory = cfg.BuildSessionFactory();
                session = sessionFactory.OpenSession();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                throw new Exception("NHibernate initialization failed", ex);
            }
        }

        /* Opens new sessions that are used by the DAO objects */
        public static ISession GetCurrentSession()
        {
            return session;
        }

        public static ISession getNewSession()
        {
            return sessionFactory.OpenSession();
        }
    }
}
